//
//  LoginViewController.m
//  MarryMe
//
//  Created by lanou3g on 16/1/12.
//  Copyright © 2016年 revocher. All rights reserved.
//
//
#import "LoginViewController.h"
#import <AVOSCloud.h>
#import "RootViewController.h"
#import "CoreDataHandle.h"
#import "UserBodyInfo.h"
#import <RongIMKit/RongIMKit.h>
#import "AFNetworking.h"
#import <CommonCrypto/CommonDigest.h>
@interface LoginViewController ()
@property (strong, nonatomic) IBOutlet UITextField *phoneNameField;
@property (strong, nonatomic) IBOutlet UITextField *passwordField;

@property (strong ,nonatomic) NSString * token;
@property(strong,nonatomic) NSString *urlStr;

@end

@implementation LoginViewController

- (void)viewDidLoad {
    [[RCIM sharedRCIM] initWithAppKey:@"8luwapkvuq27l"];
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self gethttps];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (IBAction)loginClickedAction:(id)sender {
    [AVUser logInWithMobilePhoneNumberInBackground:self.phoneNameField.text password:self.passwordField.text block:^(AVUser *user, NSError *error) {
        if (user != nil) {
            NSLog(@"登陆成功_______");
            [[RCIM sharedRCIM] connectWithToken:self.token success:^(NSString *userId) {
                
                NSLog(@"登陆成功。当前登录的用户ID：%@", userId);
            } error:^(RCConnectErrorCode status) {
                NSLog(@"登陆的错误码为:%ld", (long)status);
            } tokenIncorrect:^{
                //token过期或者不正确。
                //如果设置了token有效期并且token过期，请重新请求您的服务器获取新的token
                //如果没有设置token有效期却提示token错误，请检查您客户端和服务器的appkey是否匹配，还有检查您获取token的流程。
                NSLog(@"token错误");
            }];
            RootViewController *rootVC = [[RootViewController alloc]init];
            [self.navigationController presentViewController:rootVC animated:YES completion:nil];
        }else{
            UIAlertController * alertControlller = [UIAlertController alertControllerWithTitle:@"提示" message:@"账号或者密码错误~请重新输入" preferredStyle:    UIAlertControllerStyleAlert];
            UIAlertAction *  cancelAction = [UIAlertAction actionWithTitle:@"取消" style:  UIAlertActionStyleDefault  handler:nil];
            [alertControlller addAction: cancelAction];
            self.passwordField.text = nil;
            [self.navigationController presentViewController:alertControlller animated:YES completion:nil];            
            NSLog(@"%@",error);
        }
    }];
    

    
    
    
}

- (IBAction)passBtn:(id)sender {
    RootViewController *rootVC = [[RootViewController alloc]init];
    [self.navigationController presentViewController:rootVC animated:YES completion:nil];


//    //添加好友
    AVObject *obj = [AVObject objectWithClassName:@"ACE"];

    [obj addObjectsFromArray:@[@"什么鬼",@"啦啦啦",@"111111"] forKey:@"iiiii"];
    [obj saveInBackground];
//    [obj refresh];
    
//    AVQuery *query = [AVQuery queryWithClassName:@"ACE"];
//    AVObject *post = [query getFirstObject];
//
//
//    NSMutableArray *arr = [post objectForKey:@"iiiii"];
//    NSLog(@"________%@",arr);
    
//    NSMutableArray *  arr = [NSMutableArray array];
//    if ([obj objectForKey:@"Postlist"]!=nil) {
//        arr = [obj objectForKey:@"Postlist"];
//    }
//    AVObject *obj1 =[AVObject objectWitho
//    [obj1 objectForKeyedSubscript:@"king"];
//
//   NSMutableArray *arr =  [obj1 objectForKey:@"king"];
//    NSLog(@"%@)))))))",arr);
  
    
    
    
    
}

-(void)gethttps{
    AVQuery *query = [AVQuery queryWithClassName:@"_File"];
    [query whereKey:@"name" equalTo:[NSString stringWithFormat:@"%@.png",[AVUser currentUser].mobilePhoneNumber]];
    [query getFirstObjectInBackgroundWithBlock:^(AVObject *object, NSError *error) {
        if (object != nil) {
            self.urlStr = [object objectForKey:@"url"];
            NSLog(@"%@____________",self.urlStr);
        }
        NSLog(@"%@",error);
    }];
    
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSString *str = @"https:api.cn.ronghub.com/user/getToken.json";
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[AVUser currentUser].username,@"userId",[AVUser currentUser].username,@"name",self.urlStr,@"portraitUri", nil];
    
    
    NSMutableURLRequest * request = [[NSMutableURLRequest alloc] init];
    NSString *appKey = @"8luwapkvuq27l";
    request.timeoutInterval = 5;
    request.HTTPMethod = @"POST";
    request.URL = [NSURL URLWithString:@"https:api.cn.rong.io/user/getToken.json"];
    NSString * nonce = [NSString stringWithFormat:@"%d",arc4random()];
    NSString * timestamp = [[NSString alloc] initWithFormat:@"%ld",(NSInteger)[NSDate timeIntervalSinceReferenceDate]];
    NSString *appSec = @"jrZMWLGWC3";
    NSString *sha1 =[self  sha1: [NSString stringWithFormat:@"%@%@%@",appSec,nonce,timestamp]];
    [request setValue:[self sha1:[NSString stringWithFormat:@"%@%@%@",appSec,nonce,timestamp]] forHTTPHeaderField:@"Signature"];
    
    
    [manager.requestSerializer setValue:appKey forHTTPHeaderField:@"App-Key"];
    [manager.requestSerializer setValue:nonce forHTTPHeaderField:@"Nonce"];
    [manager.requestSerializer setValue:timestamp forHTTPHeaderField:@"Timestamp"];
    [manager.requestSerializer setValue:sha1 forHTTPHeaderField:@"Signature"];
    
    
    [manager POST:str parameters:dic success:^(AFHTTPRequestOperation *operation, id responseObject) {
        self.token = [responseObject valueForKey:@"token"];
        NSLog(@"%@++++",self.token);
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",error);
    }];
    
    
    
    
}
- (NSString *) sha1:(NSString *)input
{
    const char *cstr = [input cStringUsingEncoding:NSUTF8StringEncoding];
    NSData *data = [NSData dataWithBytes:cstr length:input.length];
    
    
    
    uint8_t digest[CC_SHA1_DIGEST_LENGTH];
    
    CC_SHA1(data.bytes, (unsigned int)data.length, digest);
    
    NSMutableString *output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
    
    for(int i=0; i<CC_SHA1_DIGEST_LENGTH; i++) {
        [output appendFormat:@"%02x", digest[i]];
    }
    
    return output;
    
    
}






/*
#pragma mark - Navigation

 In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
     Get the new view controller using [segue destinationViewController].
     Pass the selected object to the new view controller.
}
*/

@end
